define(function(require, exports, module) {

	var $ = require('jquery');
	require('../util/jquery.icheck');
	require('jbox');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('seajs/seajs/2.1.1/sea.js');
	require('jquery/jquery-file-upload/8.8.5/vendor/jquery.ui.widget.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.iframe-transport.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.fileupload.js');

	var uid = '';
	if($g_user.login == 'true'){
		uid = ''+$g_user.id;
	}else{
		uid = '-1';
	}
	
	if(uid=="-1"){
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	window.location.href=$CONFIG.base_url +"/login";
		};
		$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	}

	//加载历史信息
	$.get($CONFIG.base_url +"/api/user/check",{"uid":uid})
	.done(function(data){
		console.log(data);
		if(data == 0)
			return ;
		$("#institutionId").val(data.id);
		$("#startQualifierName").val(data.name);
		$("#applicantEmail").val(data.applicantEmail);
		$("#region-province-id").val(data.provinceId);
		$("#region-city-id").val(data.cityId);
		$("#region-county-id").val(data.districtId);
		$("#applicantPhone").val(data.applicantPhone);
		$("#appaddress").val(data.address);
		$("#startQualifierInfo").val(data.description);
		$("#verifyDoc1").val(data.verifyDoc_1);
		$("#verifyDoc1-preview").append('<img src='+data.verifyDocUrl_1+'/150x100>')
		$("#verifyDoc2").val(data.verifyDoc_2);
		$("#verifyDoc2-preview").append('<img src='+data.verifyDocUrl_2+'/150x100>')
		$("#userName").val(data.applicantName);
		$("#idCard").val(data.identityCode);
		$("#applicantPost").val(data.applicantPost);
		$("#userPhoneNo").val(data.applicantTelephone);
		$("#verifyAuth").val(data.verifyAuth);
		$("#verifyAuth-preview").append('<img src='+data.verifyAuthUrl+'/150x100>')
		$("#verifyIdCard1").val(data.verifyIdCard1);
		$("#verifyIdCard1-preview").append('<img src='+data.verifyIdCard1Url+'/150x100>')
		$("#verifyIdCard2").val(data.verifyIdCard2);
		$("#verifyIdCard2-preview").append('<img src='+data.verifyIdCard2Url+'/150x100>')
	})

	// 分配城市联动
	exports.getCityTypeSelect = function(parent, type, callback) {
		$.get($CONFIG.base_url + "/api/region/list/parent", {
			parentId : parent
		}, function(data) {
			var i, len = data.length, html = '';
			for (i = 0; i < len; i++) {
				if (i == "0") {
					html += '<option name='+data[i].name +' value="' + data[i].id + '" selected>'
							+ data[i].name + '</option>';
					tasktype = data[i].id;
					$("#region-" + type + "-id").val(data[i].id);
				} else {
					html += '<option name='+data[i].name +' value="' + data[i].id + '">'
							+ data[i].name + '</option>';
				}
			}
			$("#region-" + type + "-select").empty().append(html);
			switch (type) {
			case "province":
				exports.getCityTypeSelect(tasktype, "city");
				break;
			case "city":
				exports.getCityTypeSelect(tasktype, "county");
				break;
			default:
				break;
			}
			if (typeof (callback) == "function") {
				callback();
			}
		});
	};
	exports.getCityTypeSelect(0, "province");
	$("#region-province-select").change(function() {
		exports.getCityTypeSelect($(this).val(), "city");
		$("#region-province-id").val($(this).val());
	});
	$("#region-city-select").change(function() {
		exports.getCityTypeSelect($(this).val(), "county");
		$("#region-city-id").val($(this).val());
	});
	$("#region-county-select").change(function() {
		$("#region-county-id").val($(this).val());
	});
	
	$("#project-inroduction").on("keyup","#startQualifierInfo",function(){
		exports.checkTextLength($(this).attr("id"));
	});
	
	$("#project-inroduction").on("blur","#startQualifierInfo",function(){
		exports.checkTextLength($(this).attr("id"));
	});
	
	exports.checkTextLength = function(id){
		id="#"+id;
		var html=$(id).val();
		if(html.length>255){
			$.jBox.tip("最长不超过255个字，多余字数被截取了");
			$(id).val(html.substring(0,255));
		}
	};

	$("#file-doc1").click(function() {
		v = "verifyDoc1";
		a = $(this).attr("id");
		exports.fileUpload(v, a);
	});

	$("#file-idcard1").click(function() {
		v = "verifyIdCard1";
		a = $(this).attr("id");
		exports.fileUpload(v, a);
	});
	$("#file-doc2").click(function() {
		v = "verifyDoc2";
		a = $(this).attr("id");
		exports.fileUpload(v, a);
	});
	$("#file-idcard2").click(function() {
		v = "verifyIdCard2";
		a = $(this).attr("id");
		exports.fileUpload(v, a);
	});
	$("#file-auth").click(function() {
		v = "verifyAuth";
		a = $(this).attr("id");
		exports.fileUpload(v, a);
	});
	// 手机号码验证
	$("#userPhoneNo").keyup(
			function() {
				var phoneNo = $(this).val();
				if (!(/^1[3|4|5|8|7][0-9]\d{4,8}$/.test(phoneNo))
						|| phoneNo.length != "11") {
					$("#phoneNoNotice").text("手机号码格式不正确！请重新输入");
					$(this).focus();
					return false;
				} else {
					$("#phoneNoNotice").text("");
				}
			});
	$("#applicantPhone").keyup(function(){
		var phoneNo=$(this).val();
		if((/^(0[0-9]{2,3}\-{0,1})?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/.test(phoneNo))||(/^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$/.test(phoneNo))){
			$("#applicantPhoneNotice").text("");
		}else{
			$("#applicantPhoneNotice").text("联系电话格式不正确！请重新输入");
		}
	});
	//邮箱验证
	$("#applicantEmail").keyup(
			function() {
				var email = $(this).val();
				if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email))) {
					$("#emailNotice").text("邮箱格式不正确！请重新输入");
					$(this).focus();
					return false;
				} else {
					$("#emailNotice").text("");
				}
			});
	// 身份证验证
	$("#idCard").keyup(function() {
		var phoneNo = $(this).val();
		if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(phoneNo))) {
			$("#idCardNoNotice").text("身份证格式不正确！请重新输入");
			$(this).focus();
			return false;
		} else {
			$("#idCardNoNotice").text("");
		}
	});

	//上传图片
	exports.fileUpload = function fileUpload(v, a) {
		$("#" + a).fileupload({
			url : $CONFIG.base_url + "/common/attachment/upload/multi",
			dataType : 'json',
			formData : {
				uid : 1
			},
			add: function (e, data) {
		        var goUpload = true;
		        var uploadFile = data.files[0];
		        if (!(/\.(gif|jpg|jpeg|png)$/i).test(uploadFile.name)) {
		        	$.jBox.tip('亲~请选择正确的图片格式');
		            goUpload = false;
		        }
		        if (uploadFile.size > 1048576) { // 1mb
		        	$.jBox.tip('亲~图片太大了，最大不超过1mb哦！');
		            goUpload = false;
		        }
		        if (goUpload == true) {
		            data.submit();
		        }
		    },
			progressall : function(e, data) {
				var progress = parseInt(data.loaded / data.total * 100, 10);
				$("#loading-load").show();
				$("#loading-load").text(progress + '%');
			},
			done : function(e, data) {
				$.each(data.result, function(index, file) {
					var html = '<img data="'+ file.id+'" src="' + $CONFIG.base_url+ '/common/attachment/download/' + file.id+ '/100x100" style="margin-left:100px;"/>';
					$("#"+v+"-preview").empty().append(html);
					$('#' + v).val(file.id);
					$('.' + v + "-name").remove();
					$('.' + v + "-name").text("");
					$("#loading-load").hide();
				});
			},
		});
	};
	
	$("#user-apply-form").on("click","img",function(){
		var id=$(this).attr("data");
		$("#pre-img-modal .modal-body").empty().html('<img src="' + $CONFIG.base_url+ '/common/attachment/download/' + id+ '" style="margin-left:100px;"/>');
		$("#pre-img-modal").modal();
	});
	// 定时器
	var outtimes="6";
	exports.auto_jump = function auto_jump() {
		outtimes--;
		$.jBox.closeTip();
		$.jBox.tip('提交成功，我们将在<span style="color:#FF0000;font-weight: bold;font-size:14px;padding:0px 5px;">3个工作日</span>内处理，请耐心等待！<span style="color:#FF0000;font-weight: bold;font-size:14px;padding:0px 5px;">'+outtimes+'</span>秒后自动转跳去主页');
		if (outtimes < 0) {
			return false;
		}
		if (outtimes == 0) {
			clearInterval(time);
			$.jBox.closeTip();
			window.location=$CONFIG.base_url+"/recommend";
		} 
	};
	
	$("#orgapply-submit").click(function() {
				var vald='';
				$("#user-apply-form .required").each(function(){
					if($(this).val()==""){
						vald=$(this).attr("name");
					}
				});
				if(vald!=""){
					switch(vald){
					case "name":
						$("#startQualifierName").focus();
						$.jBox.tip("亲~名称不能为空哦！");
						return;
						break;
					case "description":
						$("#startQualifierInfo").focus();
						$.jBox.tip("亲~简介不能为空哦！");
						return;
						break;
					case "applicantEmail":
						$("#applicantEmail").focus();
						$.jBox.tip("亲~邮箱不能为空哦！");
						return;
						break;
					case "applicantPhone":
						$("#applicantPhone").focus();
						$.jBox.tip("亲~联系电话不能为空哦！");
						return;
						break;
					case "address":
						$("#appaddress").focus();
						$.jBox.tip("亲~详细地址不能为空哦！");
						return;
						break;
					case "verifyDoc_1":
						$.jBox.tip("亲~登记证书您还没有上传哦！");
						return;
						break;
					case "verifyDoc2":
						$.jBox.tip("亲~机构代码您还没有上传哦！");
						return;
						break;
					case "verifyIdCard1":
						$.jBox.tip("亲~身份证正面您还没有上传哦！");
						return;
						break;
					case "verifyIdCard2":
						$.jBox.tip("亲~身份证背面您还没有上传哦！");
						return;
						break;
					case "applicantName":
						$("#userName").focus();
						$.jBox.tip("亲~申请人姓名不能为空哦！");
						return;
						break;
					case "identityCode":
						$("#idCard").focus();
						$.jBox.tip("亲~身份证不能为空哦！");
						return;
						break;
					case "applicantPost":
						$("#applicantPost").focus();
						$.jBox.tip("亲~社会职务不能为空哦！");
						return;
						break;
					case "applicantTelephone":
						$("#userPhoneNo").focus();
						$.jBox.tip("亲~手机号码不能为空哦！");
						return;
						break;
					case "verifyAuth":
						$.jBox.tip("亲~运营者授权书您还没有上传哦！");
						return;
						break;
					}
				}

				if(!((/^(0[0-9]{2,3}\-{0,1})?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/.test($("#applicantPhone").val()))||(/^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$/.test($("#applicantPhone").val())))){
					$.jBox.tip("亲~联系电话不正确哦！");
					return;
				}
				if($("#verifyDoc1").val()==""){
					$.jBox.tip("亲~登记证书您还没有上传哦！");
					return;
				}
				if($("#verifyIdCard1").val()==""){
					$.jBox.tip("亲~身份证正面您还没有上传哦！");
					return;
				}
				if($("#verifyDoc2").val()==""){
					$.jBox.tip("亲~机构代码您还没有上传哦！");
					return;
				}
				if($("#verifyIdCard2").val()==""){
					$.jBox.tip("亲~身份证背面您还没有上传哦！");
					return;
				}
				if (!(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test($("#userPhoneNo").val()))
						|| $("#userPhoneNo").val().length != "11") {
					$.jBox.tip("亲~手机号码不正确哦！");
					return;
				}
				if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test($(
						"#idCard").val()))) {
					return;
				}
				$.jBox.tip("正在努力提交中，请稍后...");
				var date = form2js('user-apply-form', '.', true);
				var postData = $.toJSON(date);
				console.log(postData);
				$.ajax({
					url : $CONFIG.base_url + '/api/institution/add',
					type : "POST",
					data : postData,
					dataType : "json",
					contentType : "application/json",
					success : function() {
						time = setInterval(exports.auto_jump,1000);
					},
					error : function() {
						$.jBox.closeTip();
						$.jBox.tip("提交错误!");
					}
				});
			});
});
